﻿using BP.AIC.Framwork.Repository;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Product.API.Models;

namespace Product.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]

    public class NoAuthorizeController : ControllerBase
    {
        private IProductRepository<Products> _productRepository;
        private readonly ILogger<NoAuthorizeController> _logger;
        public NoAuthorizeController(ILogger<NoAuthorizeController> logger
            , IProductRepository<Products> productRepository)
        {
            _logger = logger;
            _productRepository = productRepository;
        }

        [HttpGet]
        public IActionResult Get()
        {
            string result = $"[产品服务]{DateTime.Now.ToString()}--+{Request.HttpContext.Connection.LocalIpAddress}" +
                $":{Request.HttpContext.Connection.LocalPort}";
            return Ok(result);
        }

        [HttpGet("Data")]
        public IActionResult GetData()
        {
            string result = $"[产品服务2]{DateTime.Now.ToString()}--+{Request.HttpContext.Connection.LocalIpAddress}" +
                $":{Request.HttpContext.Connection.LocalPort}";
            return Ok(result);
        }

        [HttpGet("GetTestData")]
        public IEnumerable<string> GetProductList()
        {
            return new List<string>() { "test苹果" + Random.Shared.Next(0, 100), "test桃子" + Random.Shared.Next(0, 100), "香蕉" + Random.Shared.Next(0, 100) };
        }
        /// <summary>
        /// 减库存 订阅下单事件
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        [NonAction]
        [CapSubscribe("order.services.createorder")]
        public IActionResult ReduceStock(Orders message)//Orders 为了测试
        {
            Console.WriteLine("我是cap调用");
            //业务代码
            //var product = await _context.Products.FirstOrDefaultAsync(p => p.ID == message.ProductID);
            //product.Stock -= message.Count;

            //await _context.SaveChangesAsync();
            Products products = new Products();
            products.ID = message.ID+new Random().Next(0,100);
            products.Name = "张三" + message.ID;
            products.Stock = new Random().Next(0, 100);
            int val = _productRepository.Insertable(products).ExecuteCommand();
            if (val > 0)
                return Ok(message);
            return BadRequest();
        }
    }
}
